/*! oauthapp 1.9.8 */
(function (window) {
    "use strict";

    window.oauthapp = {
        settings: $.extend({
            server: "https://www.oauthapp.com",
            access_token: Cookies.get('_oauthapp_access_token'),
            platforms: {
                web: {
                    id: 'web',
                },
                wechat: {
                    id: 'wechat',
                    cookie_user: "_oauthapp_user_wechat",
                },
                weibo: {
                    id: 'weibo',
                    cookie_user: "_oauthapp_user_weibo",
                },
                qq: {
                    id: 'qq',
                    cookie_user: "_oauthapp_user_qq",
                },
                dingtalk: {
                    id: 'dingtalk',
                    cookie_user: "_oauthapp_dingtalk_qq",
                }
            }
        }, document.scripts.namedItem("appcore").dataset)
    };

    // 获取应用的配置
    function __appPropValue(propCode) {
        var result = oauthapp.app.props.filter(function (f) {
            return f.code == propCode
        });

        if (result.length > 0) {
            return result[0].value
        }

        return ''
    }

    // 重置meat标签
    function __resetHeaderTags() {
        document.title = oauthapp.app.info.name;

        $("head").prepend('<link rel="shortcut icon" type="image/x-icon" href="' + oauthapp.app.info.logo + '" />');

        var $iframe = $('<iframe style="display:none;" src="/favicon.ico"></iframe>');

        $iframe.on('load', () => {
            setTimeout(() => {
                $iframe.off('load').remove();
            }, 0);
        }).appendTo($('body'));

        if (oauthapp.app.info.tags) {
            $("head").prepend('<meta name="keywords" content="' + oauthapp.app.info.tags + '" />');
        }
        if (oauthapp.app.info.description) {
            $("head").prepend('<meta name="description" content="' + oauthapp.app.info.description + '" />');
        }
    }

    // 应用详情
    function appInfo() {
        var settings = {
            "url": oauthapp.settings.server + "/api/apps/" + oauthapp.settings.appid + "/Info",
            "method": "GET",
            "headers": {
                "Authorization": "Bearer " + oauthapp.settings.access_token
            },
        };

        return $.ajax(settings);
    }

    // 获取web用户标识
    function webFingerIdentity() {

        var promise = new Promise(function (resolve, reject) {

            Fingerprint2.get(function (components) {

                var values = components.map(function (x) {
                    return x.value
                })

                var unionID = Fingerprint2.x64hash128(values.join(''), 31);

                resolve(unionID);

            });
        });

        return promise;
    }

    oauthapp.signUp = function (unionId, platform, password, avatar) {
        var settings = {
            "url": oauthapp.settings.server + '/api/appUsers/UnionIDSignUp',
            "method": "POST",
            "headers": {
                "Content-Type": "application/json"
            },
            "data": JSON.stringify({
                Appid: oauthapp.settings.appid,
                UnionID: unionId,
                Platform: platform,
                Pwd: password,
                Avatar: avatar
            })
        };

        return $.ajax(settings);
    }

    // UnionID 注册
    function signUp() {

        var userAvatar = __appPropValue("default_avatar") || oauthapp.app.logo;
        var userPassword = __appPropValue("default_password") || "123456";

        return oauthapp.signUp(
            oauthapp.settings.fingerIdentity,
            oauthapp.settings.platforms.web.id,
            userPassword,
            userAvatar);
    }

    oauthapp.signIn = function (unionId, platform) {
        var settings = {
            "url": oauthapp.settings.server + "/api/appUsers/UnionIDSignIn",
            "method": "POST",
            "headers": {
                "Content-Type": "application/json"
            },
            "data": JSON.stringify({
                AppID: oauthapp.settings.appid,
                UnionID: unionId,
                Platform: platform
            }),
        };

        return $.ajax(settings);
    }

    // UnionID 登录
    function signIn() {
        return oauthapp.signIn(
            oauthapp.settings.fingerIdentity,
            oauthapp.settings.platforms.web.id);
    }

    // 获取用户数据
    oauthapp.profile = function () {
        var settings = {
            "url": oauthapp.settings.server + "/api/appUsers/Profile",
            "method": "GET",
            "headers": {
                "Authorization": "Bearer " + oauthapp.settings.access_token
            }
        };

        return $.ajax(settings);
    }

    // 登录或注册获取access_token
    function autoSignIn() {
        var promise = new Promise(function (resolve, reject) {

            // 使用token登录
            if (oauthapp.settings.access_token) {
                oauthapp.profile().done(function (res) {
                    if (res.code == 200) {
                        oauthapp.appUser = res.data
                        //console.log('使用access_token获取资料');
                        resolve(res.data);
                    } else {
                        reject(res.err);
                    }
                })
            } else {
                signIn().done(function (signInRes) {
                    if (signInRes.code == 200) {
                        oauthapp.settings.access_token = signInRes.data.access_token;
                        Cookies.set('_oauthapp_access_token', oauthapp.settings.access_token, {
                            expires: signInRes.data.expires_in
                        });

                        oauthapp.profile().done(function (_profileRes) {
                            if (_profileRes.code == 200) {
                                oauthapp.appUser = _profileRes.data
                                resolve(_profileRes.data);
                            } else {
                                reject(_profileRes.err);
                            }
                        });

                        //console.log('使用web identity登录');
                    } else {
                        signUp().done(function (signUpRes) {
                            if (signUpRes.code == 200) {
                                oauthapp.settings.access_token = signUpRes.data.access_token;
                                Cookies.set('_oauthapp_access_token', oauthapp.settings.access_token, {
                                    expires: signUpRes.data.expires_in
                                });

                                oauthapp.profile().done(function (_profileRes) {
                                    if (_profileRes.code == 200) {
                                        oauthapp.appUser = _profileRes.data
                                        resolve(_profileRes.data);
                                    } else {
                                        reject(_profileRes.err);
                                    }
                                });

                                // console.log('使用web identity注册');
                            } else {
                                console.err(signUpRes.err);
                            }
                        });
                    }
                })
            }

        });

        return promise;
    }

    // 初始化 应用
    oauthapp.ready = function () {
        var promise = new Promise(function (resolve, reject) {
            Promise.all([
                appInfo(),
                webFingerIdentity()
            ]).then(function (res) {
                oauthapp.app = res[0].data;
                oauthapp.settings.fingerIdentity = res[1];
                __resetHeaderTags();
                resolve(oauthapp.app);
            })
        });

        return promise;
    }

    // 初始化 应用 + 用户
    oauthapp.allReady = function () {
        var promise = new Promise(function (resolve, reject) {
            oauthapp.ready().then(function () {
                autoSignIn().then(x => {
                    //  fn(oauthapp.app, oauthapp.appUser);
                    resolve(oauthapp.app, oauthapp.appUser);
                })
            })
        });

        return promise;
    }

    // 更新资料
    oauthapp.profilePut = function (_avatar, _nickName, _data) {

        oauthapp.appUser.data = _data;
        oauthapp.appUser.avatar = _avatar;
        oauthapp.appUser.nickName = _nickName;

        if (!oauthapp.appUser.data) {
            oauthapp.appUser.data = '{}';
        }

        if (!oauthapp.appUser.avatar) {
            oauthapp.appUser.avatar = '';
        }

        if (!oauthapp.appUser.nickName) {
            oauthapp.appUser.nickName = '';
        }

        return $.ajax({
            url: oauthapp.settings.server + '/api/AppUsers/Profile',
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
                'Authorization': 'Bearer ' + oauthapp.settings.access_token
            },
            data: JSON.stringify({
                avatar: oauthapp.appUser.avatar,
                nickName: oauthapp.appUser.nickName,
                data: JSON.stringify(oauthapp.appUser.data),
            })
        });
    }

})(window)